package com.cai.util;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import javax.sql.DataSource;
import java.beans.PropertyVetoException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * @author RuoLi
 */
public class C3p0Util {

    public static DataSource ds = null;
    static {
        ComboPooledDataSource cpds = new ComboPooledDataSource();
        try {
            InputStream is = C3p0Util.class.getClassLoader().getResourceAsStream("db.properties");
            Properties properties = new Properties();
            //读取properties文件
            properties.load(is);
            cpds.setDriverClass(properties.getProperty("c3p0.DriverClass"));
            cpds.setJdbcUrl(properties.getProperty("c3p0.JdbcUrl"));
            cpds.setUser(properties.getProperty("c3p0.User"));
            cpds.setPassword(properties.getProperty("c3p0.Password"));
            cpds.setInitialPoolSize(Integer.parseInt(properties.getProperty("c3p0.InitialPoolSize")));
            cpds.setMaxPoolSize(Integer.parseInt(properties.getProperty("c3p0.MaxPoolSize")));
            //maxIdleTime
            //default : 0 单位 s
            //连接的最大空闲时间，如果超过这个时间，某个数据库连接还没有被使用，则会断开掉这个连接
            //如果为0，则永远不会断开连接
            cpds.setMaxIdleTime(Integer.parseInt(properties.getProperty("c3p0.MaxIdleTime")));
            //这个配置主要是为了减轻连接池的负载，比如连接池中连接数因为某次数据访问高峰导致创建了很多数据连接
            //但是后面的时间段需要的数据库连接数很少,必须小于maxIdleTime
            cpds.setMaxIdleTimeExcessConnections(Integer.parseInt(properties.getProperty("c3p0.MaxIdleTimeExcessConnections")));
            cpds.setMinPoolSize(Integer.parseInt(properties.getProperty("c3p0.MinPoolSize")));
            ds = cpds;
        }catch (PropertyVetoException | IOException e){
            e.printStackTrace();
        }
    }

    public static DataSource getDataSource(){
        return ds;
    }
}
